use std::env;

pub struct Config {
    pub query: String,
    pub fileName: String,
    pub case_sensitive: bool,
}

impl Config {
    pub fn new(mut args: env::Args) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("没有足够的参数");
        }
        args.next();
        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("无法获取查询参数")
        };
        let fileName = match args.next() {
            Some(arg) => arg,
            None => return Err("无法获取文件名")
        };
        let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
        Ok(Config { query, fileName, case_sensitive })
    }
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let results: Vec<&str> = contents.lines()
        .filter(|item| item.contains(query))
        .collect();

    // let mut results = Vec::new();
    // for item in contents.lines() {
    //     if item.contains(query) {
    //         results.push(item);
    //     }
    // };
    results
}

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let query = query.to_lowercase();

    let results: Vec<&str> = contents.lines()
        .filter(|item| item.to_lowercase().contains(&query))
        .collect();

    // let mut results = Vec::new();
    // for item in contents.lines() {
    //     if item.to_lowercase().contains(&query) {
    //         results.push(item);
    //     }
    // };
    results
}


#[cfg(test)]
mod Tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe fast,productive
pick three.
Duct tape.";
        println!("{:?}", search(query, contents));
        assert_eq!(vec!["safe fast,productive"], search(query, contents));
    }
}
